<?php

/**
 * image actions.
 *
 * @package    PHOTO_GALLERY
 * @subpackage image
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class imageActions extends sfActions {

    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request) {
        $this->forward('default', 'module');
    }

    public function executeRate(sfWebRequest $request) {
        $userId =   $this->getUser()->getAttribute('userId');
        $rate   =   $request->getParameter('rate');
        $imgId  =   $request->getParameter('imageId');
        $r = Doctrine_Core::getTable('ImageRates')->createQuery()->select()->where('image_id = ?', $imgId)->andWhere('user_id = ?', $userId)->fetchOne();
        
        $imgRate = Doctrine_Core::getTable('Images')->find($imgId);
        $numRates = $imgRate->getNoOfRates();
        $oldAvg = $imgRate->getAvgRate();
        
        if($r == false){//i.e. new rate
            $r = new ImageRates();
            $r->setImageId($imgId);
            $r->setUserId($userId);
            $r->setRate($rate);
            $imgRate->setNoOfRates($numRates +1);
            $newAvg = ($oldAvg * $numRates + $rate)/ ($numRates+1); 
        }
        else{//edit rate
            $oldRate = $r->getRate();
            $r->setRate($rate);
            $newAvg = ($oldAvg * $numRates + $rate - $oldRate)/ ($numRates); 
        }
        $imgRate->setAvgRate($newAvg);
        $imgRate->save();
        $r->save();
        return $this->renderText(round($imgRate->getAvgRate()) );
    }
    public function executeAddToFav(sfWebRequest $request) {
        $imgId  =   $request->getParameter('imgId');
        $fav    =   new Favorites();
        $fav->setImageId($imgId);
        $fav->setUserId($this->getUser()->getAttribute('userId'));
        $fav->save();
        return $this->renderText('done');
    }
    
    public function executeRemoveFromFav(sfWebRequest $request) {
        $imgId  =   $request->getParameter('imgId');
        $fav    =   new Favorites();
        $fav->setImageId($imgId);
        $fav->setUserId($this->getUser()->getAttribute('userId'));
        $fav->delete();
        return $this->renderText('done');
    }

}
